import { keyData, indexData } from './mysql-data'
const { $fn, $ } = window
const modKey = ({ database, table_name, Field, Type, Key, tableRef, e }) => {
	e.stopPropagation()
	window.$formModalRef().open({
		modal:{
			title 	: <span>修改字段【<b className='c3 ar'>{Field}</b>】索引</span>,
			width 	: '35%',
			// controls: { ok: !Key }
		},
		form: {
			labelWidth: 's5',
			api: 'mysql/structure/mod_key',
			way:'put',
			infoApi : false,
			param: { database, table_name, Field, Type, Key: Key ? Key : 'UNI' },
			onValid: ({ Key }) => {
				// if( Key === 'PRI' ){
				// 	let d = $.ref(tableRef).tableRef().data().some( v => v.Field !== Field && v.Key === 'PRI')
				// 	if( d ){
				// 		$fn.msg.warning('一个表中只能有一个主键: Primary Key')
				// 		return false
				// 	}
				// }
				if( [ 'tinytext' ].includes(Type) ){
					$fn.msg.warning(`【${Type}】类型无法设置${indexData?.[Key]}`)
					return false
				}
				if( Key==='FULL' && ( !Type.includes('text') && !Type.includes('char') )){
					$fn.msg.warning(`仅文本类型可设置${indexData?.[Key]}`)
					return false
				}
				return true
			},
			data: [
				{ label: '字段名', name:'Field', disabled:1 },
				{ label: '数据类型', name:'Type', disabled:1 },
				{ label: '索引', name: 'Key', type:'select', data:keyData, disabled: Key },
			],
			onOk : () => {
				$.ref(tableRef).tableRef().search({ scroll:0 })
			}
		}
	})
}
const delKey = ({ database, table_name, Field, Type, Key, tableRef, e }) => {
	e.stopPropagation()
	const config = {
		modal:{
			title 	: <span>删除【<b className='c3 ar'>{Field}</b>】{ indexData?.[Key] }</span>,
			width 	: '35%',
		},
		backParam: { database, table_name, column_name: Field },
		form: {
			labelWidth: 's5',
			api: 'mysql/structure/del_key',
			way:'put',
			infoApi : 'mysql/find_key_name',
			param: { database, table_name, Field, Type },
			data: [
				{ label: '字段名', name:'Field', disabled:1 },
				{ label: '数据类型', name:'Type', disabled:1 },
				{ label: '主键名称', name: 'key_name', type:'select', data:[]},
			],
			onOk : () => {
				$.ref(tableRef).tableRef().search({ scroll:0 })
			}
		},
		onEnd: ({ data, update, formRef }) => {
			let d = data.map(v => v.Key_name)
			let _k = $fn.getRow(config, 'key_name')
			_k.data = d
			_k.disabled = d.length === 1
			formRef.setValue({ key_name: d?.[0] })
			update()
		}
	}
	window.$formModalRef().open(config)
}

const Index = ({ database, table_name, Field, Type, Key, tableRef, e }) => {
	if( Key ) {
		delKey({ database, table_name, Field, Type, Key, tableRef, e })
	}else{
		modKey({ database, table_name, Field, Type, Key, tableRef, e })
	}
}

export default Index